package com.lgj.gateway.filter;

import lombok.Data;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.util.Arrays;
import java.util.List;

/**
 * @author: guangjie.liao
 * @Date: 2023/8/16 13:48
 * @Description: 局部过滤的命名固定为 【前缀+GatewayFilterFactory】
 */
@Component
public class PartGatewayFilterFactory extends AbstractGatewayFilterFactory<PartGatewayFilterFactory.Config> {

    private static String FAIL_URL = "http://localhost:8001/test/fail";
    /**
     * 重新父类apply方法，使用Config接收配置参数
     * @param config
     * @return
     */
    @Override
    public GatewayFilter apply(Config config) {
        //这里可以做具体的拦截处理，如限流，规则校验
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest().mutate().build();
            URI uri = exchange.getRequest().getURI();
            String query = uri.getRawQuery();
            //请求地址中如果不包括token惨，就跳转到失败地址
            if (query.indexOf("token") == -1){
                request = exchange.getRequest().mutate().uri(URI.create(FAIL_URL)).build();
                return chain.filter(exchange.mutate().request(request).build());
            }
            return chain.filter(exchange.mutate().request(request).build());
        };
    }

    /**
     * 指定配置参数接收顺序
     * @return
     */
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("arg1","arg2","arg3","arg4","arg5");
    }

    /**
     * 定义配置参数接收字段
     */
    @Data
    public static class Config{
        private Object arg1;
        private Object arg2;
        private Object arg3;
        private Object arg4;
        private Object arg5;
    }
}
